<template>
  <v-page background="#f5f6fa" footer-background="white" :loading="loading">
    <template #header>
      <v-navbar
        :title="product ? product.detail_page_title || '商品详情' : ''"
      />
    </template>
    <template #default>
      <template v-if="product">
        <product-details-carousel v-if="product.carousel_flag" />
        <product-details-swiper :product="product" />
        <view v-if="recommendTag" class="product-event">
          <view class="event-background">
            <v-image
              oss-src="product-details-background.png"
              mode="widthFix"
              height="365rpx"
              width="100vw"
            />
          </view>
          <view class="content">
            <view class="main-text">
              {{ recommendTag.name }}
            </view>
            <view class="sub-text">
              {{ recommendTag.tag }}
            </view>
            <wd-count-down :time="time">
              <template #default="{ current }">
                <view class="count-down-container">
                  <view class="count-down">
                    {{ parseTime(current.hours) }}
                  </view>
                  <view class="count-down-colon">
                    :
                  </view>
                  <view class="count-down">
                    {{ parseTime(current.minutes) }}
                  </view>
                  <view class="count-down-colon">
                    :
                  </view>
                  <view class="count-down">
                    {{ parseTime(current.seconds) }}
                  </view>
                </view>
              </template>
            </wd-count-down>
          </view>
        </view>
        <product-details-sales :product="product" />
        <product-details-group-purchase
          v-if="product.group_purchase_flag"
          :product="product"
          @click-purchase="showOrder('order')"
        />
        <product-details-sku
          :product="product"
          @show-select="showOrder('order')"
          @show-guarantee="isShowGuarantee = true"
          @show-property="isShowProperty = true"
        />
        <product-details-comment
          v-if="product.spu_comment_show_flag && (comments?.comments.length || commentGroupList?.length)"
          :product="product"
          :comments="comments"
          :comment-group-list="commentGroupList"
        />
        <!-- <product-details-question :product="product" /> -->
        <product-details-merchant
          v-if="product.store_status === 'ENABLED'"
          :product="product"
        />
        <view class="product-details">
          <view class="product-details-header">
            商品详情
          </view>
          <v-image
            v-for="(image, index) in product.detail_image"
            :key="index"
            :src="image"
            width="100vw"
            mode="widthFix"
          />
        </view>
      </template>
    </template>
    <template #footer>
      <view class="product-footer">
        <!-- #ifdef MP-ALIPAY -->
        <view v-if="tntInstId && scene" class="footer-button">
          <v-icon size="48rpx" src="@/static/icons/service-icon.svg" />
          <view class="button-text">
            客服
          </view>
          <view class="footer-button-float">
            <contact-button
              :tnt-inst-id="tntInstId"
              :scene="scene"
              size="48rpx"
              icon="/static/icons/service-blank.svg"
            />
          </view>
        </view>
        <!-- #endif -->
        <view class="footer-button" @click="switchToCart">
          <v-icon size="48rpx" src="@/static/icons/product-details-cart.svg" />
          <view class="button-text">
            购物车
          </view>
        </view>
        <view class="footer-button-group">
          <view class="group-button add-cart" @click="showOrder('cart')">
            加入购物车
          </view>
          <view
            class="group-button buy-immediately"
            @click="showOrder('order')"
          >
            立即下单
          </view>
        </view>
      </view>
    </template>
    <template #popup>
      <product-details-guarantee-popup
        v-if="product"
        v-model:show="isShowGuarantee"
        :product="product"
      />
      <product-details-property-popup
        v-if="product"
        v-model:show="isShowProperty"
        :product="product"
      />
      <product-details-select-popup
        v-if="product"
        v-model:show="isShowSelect"
        :type="orderType"
        :product="product"
      />
    </template>
  </v-page>
</template>

<script setup lang="ts">
import usePageRecord from '@/composables/use-page-record';
import ProductDetailsSwiper from './modules/product-details-swiper.vue';
import ProductDetailsCarousel from './modules/product-details-carousel.vue';
import ProductDetailsSales from './modules/product-details-sales.vue';
import ProductDetailsGroupPurchase from './modules/product-details-group-purchase.vue';
import ProductDetailsSku from './modules/product-details-sku.vue';
import ProductDetailsComment from './modules/product-details-comment.vue';
// import ProductDetailsQuestion from './modules/product-details-question.vue';
import ProductDetailsGuaranteePopup from './modules/product-details-guarantee-popup.vue';
import ProductDetailsPropertyPopup from './modules/product-details-property-popup.vue';
import ProductDetailsSelectPopup from './modules/product-details-select-popup.vue';
import ProductDetailsMerchant from './modules/product-details-merchant.vue';

onLoad(usePageRecord);

const productId = ref('');
const product = ref<SpuVO>();
const merchant = ref<MerchantVO>();
const tntInstId = computed(() => {
  if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
  return merchant.value?.customer_service_setting?.tenant_id;
});
const scene = computed(() => {
  if (merchant.value?.customer_service_status !== 'ENABLED') return undefined;
  return merchant.value?.customer_service_setting?.chat_window_id;
});
const loading = ref(true);
const record = async () => {
  if (!product.value?.merchant_id) return;
  $api.postMerchantView(
    { merchant_id: product.value.merchant_id },
    { notifyApiError: false }
  );
};
const storeDecorationId = ref<string>();
const recordStoreDecoration = async () => {
  if (!storeDecorationId.value) return;
  $api.getSearchIdStoreDecorationIdDetail(
    productId.value,
    storeDecorationId.value
  );
};
onLoad(async (query) => {
  productId.value = query?.id as string;
  storeDecorationId.value = query?.storeid as string | undefined;
  loading.value = true;
  await getDetails();
  if (!product.value) {
    loading.value = false;
    uni.navigateBack();
    return;
  }
  await Promise.all([
    getMerchant(),
    getComments(),
    getGroupCommentList(),
    record()
  ]);
  loading.value = false;
  if (!product.value) uni.navigateBack();
  if (storeDecorationId.value) {
    recordStoreDecoration();
  }
});

onShow(async () => {
  await Promise.all([getComments(), getGroupCommentList()]);
});

const recommendTag = computed(() => {
  return product.value?.spu_tag_list?.find(
    (item) => item.type === 'RECOMMEND_TAG'
  );
});

const time = computed(() => {
  const nextDay = new Date();
  nextDay.setDate(nextDay.getDate() + 1);
  nextDay.setHours(0, 0, 0, 0);
  return nextDay.getTime() - new Date().getTime();
});

const parseTime = (time: number) => {
  return time < 10 ? `0${time}` : time;
};

const getDetails = async () => {
  const response = await $api.getSearchIdDetail(productId.value);

  switch (response.__error) {
    case undefined:
      product.value = response.data;
      product.value.handy_sku_list = product.value.handy_sku_list
        ? product.value.handy_sku_list.filter((item) => item.inventory)
        : [];
      break;
  }
};
const getMerchant = async () => {
  if (!product.value?.merchant_id) return;
  const response = await $api.getMerchantId(product.value.merchant_id);
  switch (response.__error) {
    case undefined:
      merchant.value = response.data;
      break;
  }
};

const comments = ref<SpuOrderCommentVO>();
const getComments = async () => {
  if (!product.value?.id) return;
  const response = await $api.getOrderCommentSpuid(product.value.id, {
    page_no: 1,
    page_size: 2
  });
  switch (response.__error) {
    case undefined:
      comments.value = response.data;
      break;
    default:
  }
};

const commentGroupList = ref<SpuCommentGroupCommentOrderVO[]>();
const getGroupCommentList = async () => {
  if (!product.value?.id) return;
  const response = await $api.getOrderCommentGroupCommentSpuid(
    product.value.id,
    { page_no: 1, page_size: 2 }
  );
  switch (response.__error) {
    case undefined:
      commentGroupList.value = response.data.list;
      break;
    default:
  }
};

const switchToCart = () => {
  uni.switchTab({ url: '/pages/cart/cart-page' });
};

const isShowGuarantee = ref(false);
const isShowProperty = ref(false);

const isShowSelect = ref(false);
const orderType = ref<'cart' | 'order'>('cart');
const showOrder = (type: 'cart' | 'order') => {
  orderType.value = type;
  isShowSelect.value = true;
};
</script>

<style lang="scss" scoped>
.product-event {
  position: relative;
  height: 365rpx;
  margin-top: -28rpx;
  margin-bottom: calc(-365rpx + 28rpx + 92rpx - 24rpx);
  padding-top: 28rpx;
  box-sizing: border-box;
  .content {
    height: 92rpx;
    position: relative;
    display: flex;
    align-items: center;
    gap: 12rpx;
    padding: 0 24rpx;
    .main-text {
      color: white;
      font-weight: bold;
      font-size: 32rpx;
    }
    .sub-text {
      flex: 1;
      min-width: 0;
      color: white;
      font-weight: 300;
    }
    .count-down-container {
      display: flex;
      align-items: center;
      height: 48rpx;
      line-height: 48rpx;
    }
    .count-down {
      height: 48rpx;
      line-height: 48rpx;
      width: 48rpx;
      border-radius: 4rpx;
      background-color: white;
      color: #ff2f3b;
      text-align: center;
    }
    .count-down-colon {
      height: 48rpx;
      line-height: 48rpx;
      color: white;
      margin: 0 12rpx;
    }
  }
  .event-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 365rpx;
    display: block;
  }
}

.product-details {
  background-color: white;
  border-radius: 16rpx 16rpx 0 0;
  .product-details-header {
    line-height: 93rpx;
    padding: 0 48rpx;
    font-weight: bold;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.product-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 100rpx;
  .footer-button {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6rpx;
    width: 70rpx;
    .button-text {
      font-size: 22rpx;
    }
    .footer-button-float {
      position: absolute;
      z-index: 1;
      top: 50%;
      left: 50%;
      height: 50rpx;
      width: 50rpx;
      transform: translate(-50%, -50%);
    }
  }
  .footer-button-group {
    display: flex;
    .group-button {
      width: 267rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: bold;
    }
    .add-cart {
      color: #ff2f3b;
      background-color: rgba(255, 47, 59, 0.102);
      border-radius: 40rpx 0 0 40rpx;
    }
    .buy-immediately {
      color: white;
      background-color: #ff2f3b;
      border-radius: 0 40rpx 40rpx 0;
    }
  }
}
</style>
